<template>
  <div class="app-container">
    <div class="search_nav">
      <div class="left_input">
        <div class="left_input_desc vue-ellipsis">
          <span>请输入查询条件:</span>
        </div>
        <div class="input">
          <el-input
            v-model="inputStr"
            size="small"
            placeholder="请输入查询条件"
          ></el-input>
        </div>
      </div>
      <div class="right_setting">
        <el-button-group class="right_setting_left">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-search"
            @click="onQueryStudentClick"
            >查询</el-button
          >
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-document"
            @click="onQueryAllStudentClick"
            >显示全部</el-button
          >
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="onAddStudentClick"
            >添加</el-button
          >
        </el-button-group>
        <el-upload
          action=""
          :show-file-list="false"
          :http-request="uploadExcelPost"
        >
          <el-button size="mini" type="primary">导入Excel</el-button>
        </el-upload>
        <div>
          <el-button
            class="export_excel"
            size="mini"
            type="primary"
            @click="exportToExcel"
            >导出Excel</el-button
          >
        </div>
      </div>
    </div>

    <el-table
      ref="table"
      v-loading="listLoading"
      element-loading-text="Loading"
      :data="listData"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="编号" width="80" align="center">
        <template slot-scope="scope"
          ><div class="serial_number">{{ scope.$index + 1 }}</div></template
        >
      </el-table-column>
      <el-table-column label="学号" width="120" align="center">
        <template slot-scope="scope">{{ scope.row.sno }}</template>
      </el-table-column>
      <el-table-column label="姓名" width="120" align="center">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column label="性别" width="80" align="center">
        <template slot-scope="scope">{{ scope.row.gender }}</template>
      </el-table-column>
      <el-table-column label="出生日期" width="120" align="center">
        <template slot-scope="scope">{{ scope.row.birthday }}</template>
      </el-table-column>
      <el-table-column label="手机号码" width="120" align="center">
        <template slot-scope="scope">{{ scope.row.mobile }}</template>
      </el-table-column>
      <el-table-column label="邮箱地址" width="240" align="center">
        <template slot-scope="scope">{{ scope.row.email }}</template>
      </el-table-column>
      <el-table-column label="住址" min-width="220" align="center">
        <template slot-scope="scope">{{ scope.row.address }}</template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            icon="el-icon-more"
            circle
            @click="onLookDetail(scope.row)"
          ></el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            circle
            @click="onEditStudentInfo(scope.row)"
          ></el-button>
          <el-popconfirm
            confirmButtonText="好的"
            cancelButtonText="不用了"
            icon="el-icon-info"
            iconColor="red"
            style="margin-left: 10px"
            title="这是一段内容确定删除吗？"
            @onConfirm="onDeleteStudent(scope.row.sno)"
          >
            <el-button
              slot="reference"
              size="mini"
              :loading="sureDelete"
              type="danger"
              icon="el-icon-delete"
              circle
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="app_bottom">
      <el-popconfirm
        confirmButtonText="好的"
        cancelButtonText="不用了"
        icon="el-icon-info"
        iconColor="red"
        title="选中的学员确定删除吗？"
        @onConfirm="onDeleteMoreStudent"
      >
        <el-button
          slot="reference"
          size="mini"
          :loading="sureDeletes"
          type="danger"
          icon="el-icon-delete"
          >批量删除</el-button
        >
      </el-popconfirm>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getpaginationList"
      />
    </div>
    <el-dialog
      :title="dialogTitle"
      size="mini"
      :visible.sync="dialogVisible"
      width="50%"
      center
      :close-on-click-modal="false"
      @close="closeDialogForm"
    >
      <el-form
        ref="form"
        :inline="true"
        label-width="130px"
        style="margin-left: 30px"
        label-position="right"
        size="mini"
        :rules="rules"
        :model="studentForm"
      >
        <el-upload
          class="avatar-uploader"
          style="text-align: center; margin-bottom: 20px; margin-left: -30px"
          :show-file-list="false"
          action=""
          :disabled="isLook === 1"
          :http-request="uploadPicturePost"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="studentForm.image"
            :src="studentForm.image"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <el-form-item size="mini" label="学号：" prop="sno">
          <el-input
            v-model="studentForm.sno"
            :disabled="isLook != 0"
            placeholder="学号"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名：" prop="name">
          <el-input
            v-model="studentForm.name"
            :disabled="isLook === 1"
            placeholder="姓名"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="性别："
          style="margin-left: 0px; margin-right: 0px"
          prop="gender"
        >
          <el-select
            v-model="studentForm.gender"
            placeholder="请选择性别"
            style="width: 92%"
            :disabled="isLook === 1"
          >
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="出生日期："
          style="margin-left: -5px; margin-right: 0px"
          prop="birthday"
        >
          <el-date-picker
            v-model="studentForm.birthday"
            type="date"
            style="width: 85%"
            :disabled="isLook === 1"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手机号码：" prop="mobile">
          <el-input
            v-model="studentForm.mobile"
            placeholder="手机号码"
            :disabled="isLook === 1"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱地址：" prop="email">
          <el-input
            v-model="studentForm.email"
            placeholder="邮箱地址"
            :disabled="isLook === 1"
          ></el-input>
        </el-form-item>
        <el-form-item label="家庭住址：" prop="address">
          <el-input
            v-model="studentForm.address"
            style="width: 262%"
            placeholder="家庭住址"
            :disabled="isLook === 1"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          v-show="isLook != 1"
          size="mini"
          type="primary"
          :loading="sureDialog"
          @click="onSureClick"
          >确定</el-button
        >
        <el-button size="mini" type="info" @click="closeDialogForm"
          >取消</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
//分页
import Pagination from '@/components/Pagination'
import {
  studentList,
  queryStudentList,
  snoCheck,
  studentAdd,
  studentUpdate,
  studentDelete,
  studentsDelete,
  upLoadImg,
  importStudentExcel,
  exportStudentExcel,
} from '@/api/studentinfo'
export default {
  name: 'Studentinformation',
  components: { Pagination },
  data() {
    // 校验学号是否存在
    const rulesSNo = (rule, value, callback) => {
      if (this.isLook != 0) {
        callback()
        return
      }
      // 使用Axios进行校验
      snoCheck({
        sno: value,
      })
        .then((res) => {
          if (res.data === 1) {
            callback(new Error('学号已存在'))
          } else {
            callback()
          }
        })
        .catch((err) => {
          callback(new Error('校验学号出现异常！'))
        })
    }
    return {
      inputStr: '',
      //总条数
      total: 0,
      listQuery: {
        page: 1, //当前第几页
        limit: 10, //每页多少数据
      },
      listLoading: false,
      listData: [],
      dialogVisible: false,
      dialogTitle: '',
      isLook: 0, //标识dialog状态，0：添加，1：查看，2：编辑
      studentForm: {
        sno: '',
        name: '',
        gender: '',
        birthday: '',
        mobile: '',
        email: '',
        address: '',
        image: '',
      },
      rules: {
        sno: [
          { required: true, message: '请输入学生学号', trigger: 'blur' },
          {
            pattern: /^[9][5]\d{3}$/,
            message: '学号必须是95开头的五位数',
            trigger: 'blur',
          },
          {
            validator: rulesSNo,
            trigger: 'blur',
          },
        ],
        name: [
          { required: true, message: '请输入学生名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' },
        ],
        gender: [
          {
            required: true,
            message: '请选择学生名称性别',
            trigger: 'change',
          },
        ],
        birthday: [
          {
            required: true,
            message: '请选择出生日期',
            trigger: 'change',
          },
        ],
        mobile: [
          { required: true, message: '请输入学生手机号码', trigger: 'blur' },
          {
            pattern: /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|191|199|(147))\d{8}$/,
            message: '手机号码格式不正确',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入学生邮箱', trigger: 'blur' },
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: '邮箱格式不正确',
            trigger: 'blur',
          },
        ],
        address: [
          { required: true, message: '请输入学生地址', trigger: 'blur' },
        ],
      },
      sureDialog: false,
      sureDelete: false,
      sureDeletes: false,
      selectStudent: [],
    }
  },
  mounted() {
    this._getList()
  },
  methods: {
    // 查询学生数据
    onQueryStudentClick() {
      if (Object.keys(this.inputStr).length == 0) {
        this.$message.info('请输入查询条件')
        return
      }
      this._queryStudentList()
    },
    // 查询全部数据
    onQueryAllStudentClick() {
      this.inputStr = ''
      this._getList()
    },
    //添加学生信息
    onAddStudentClick() {
      this.dialogTitle = '添加学生信息'
      this.dialogVisible = true
    },
    // 查看学生信息
    onLookDetail(item) {
      this.dialogTitle = '查看学生信息'
      this.studentForm = JSON.parse(JSON.stringify(item))
      this.isLook = 1
      this.dialogVisible = true
    },
    // 编辑学生信息
    onEditStudentInfo(item) {
      this.dialogTitle = '编辑学生信息'
      this.studentForm = JSON.parse(JSON.stringify(item))
      this.isLook = 2
      this.dialogVisible = true
    },
    //关闭弹出框
    closeDialogForm() {
      this.dialogVisible = false
      this.isLook = 0
      this.$refs.form.resetFields()
      this.studentForm.image = ''
    },
    //确认
    onSureClick() {
      if (!this.studentForm.image) {
        this.$message.error('学员图片不能为空')
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.isLook === 0) {
            //添加
            this._submitAddStudent()
          } else if (this.isLook === 2) {
            // 编辑
            this._submitUpdateStudent()
          }
        } else {
          return false
        }
      })
    },
    // 删除数据
    onDeleteStudent(sno) {
      this.sureDelete = true
      studentDelete({
        sno: sno,
      })
        .then((res) => {
          this.$message.success(res.data)
          this._getList()
        })
        .catch((err) => {})
        .finally(() => {
          this.sureDelete = false
        })
    },
    // 选择的学员
    handleSelectionChange(data) {
      this.selectStudent = data
    },
    //批量删除
    onDeleteMoreStudent() {
      if (this.selectStudent.length == 0) {
        return
      }
      this.sureDeletes = true
      studentsDelete({ students: this.selectStudent })
        .then((res) => {
          this.$message.success(res.data)
          this._getList()
        })
        .catch((err) => {})
        .finally(() => {
          this.sureDeletes = false
        })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('图片格式不支持，请上传jpg或者png格式')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传图片
    uploadPicturePost(file) {
      const fileReq = new FormData()
      fileReq.append('avatar', file.file)
      upLoadImg(fileReq)
        .then((res) => {
          this.studentForm.image = process.env.VUE_APP_BASE_API + res.data
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 导入excel
    uploadExcelPost(file) {
      const fileReq = new FormData()
      fileReq.append('excel', file.file)
      importStudentExcel(fileReq)
        .then((res) => {
          if (res.data.error > 0) {
            this.$message.info(
              '本次导入完成，成功：' +
                res.data.success +
                '条，失败：' +
                res.data.error +
                '条，失败的学员学号为：' +
                JSON.stringify(res.data.info)
            )
          } else {
            this.$message.info('本次导入完成，成功!')
          }

          this._getList()
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //导出excel
    exportToExcel() {
      exportStudentExcel()
        .then((res) => {
          const url = process.env.VUE_APP_BASE_API + res.data
          window.open(url)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 分页
    getpaginationList() {
      if (Object.keys(this.inputStr).length == 0) {
        this._getList()
      } else {
        this._queryStudentList()
        
      }
    },
    // 添加数据
    _submitAddStudent() {
      this.sureDialog = true
      studentAdd(this.studentForm)
        .then((res) => {
          this.$message.success(res.data)
          this._getList()
        })
        .catch((err) => {})
        .finally(() => {
          this.sureDialog = this.dialogVisible = false
        })
    },
    // 修改数据
    _submitUpdateStudent() {
      this.sureDialog = true
      studentUpdate(this.studentForm)
        .then((res) => {
          this.$message.success(res.data)
          this._getList()
        })
        .catch((err) => {})
        .finally(() => {
          this.sureDialog = this.dialogVisible = false
        })
    },

    // 查询数据
    _queryStudentList() {
      this.listLoading = true
      queryStudentList({
        perpage: this.listQuery.limit,
        page: this.listQuery.page,
        inputstr: this.inputStr,
      })
        .then((res) => {
          this.total = res.data.total
          this.listData = res.data.lists
        })
        .catch((err) => {})
        .finally(() => {
          this.listLoading = false
        })
    },
    //得到分页数据
    _getList() {
      this.listLoading = true
      studentList({
        perpage: this.listQuery.limit,
        page: this.listQuery.page,
      })
        .then((res) => {
          this.total = res.data.total
          this.listData = res.data.lists
        })
        .catch((err) => {})
        .finally(() => {
          this.listLoading = false
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.app-container {
  .search_nav {
    padding-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left_input {
      align-items: center;
      display: flex;
      .left_input_desc {
        color: #888888;
        font-size: 16px;
        padding-right: 10px;
      }
      .input {
        width: 200px;
        margin-right: 10px;
      }
    }
    .right_setting_left {
      margin-right: 20px;
    }
    .right_setting {
      display: flex;
      margin-left: 50px;
    }
  }
  .serial_number {
    text-align: left;
  }
  .app_bottom {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .export_excel {
    margin-left: 10px;
  }
}
::v-deep .avatar-uploader .el-upload--text {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 22px;
  color: #ccc;
  width: 108px;
  height: 108px;
  line-height: 108px;
  text-align: center;
}
::v-deep.avatar {
  width: 108px;
  height: 108px;
  display: block;
}
</style>
